/*
 * Copyright (c) dabing.io
 * All rights reserved.
 * OSSServiceImpl.java
 */

package com.ueboot.weishop.service.file.impl;

import com.aliyun.oss.OSSClient;
import com.ueboot.weishop.service.file.FileManagerService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;

/**
 * 描述: 阿里云OSS 文件存储
 *
 * @author yangkui
 * @since 1.0
 */
@Service(value = "ossFileManagerService")
public class OSSFileManagerServiceImpl implements FileManagerService {

    @Value(value = "${file.oss.bucket}")
    private String bucket;
    @Value(value = "${file.oss.schema}")
    private String schema;
    @Value(value = "${file.oss.endpoint.external}")
    private String endpoint;
    @Value(value = "${file.oss.endpoint.internal}")
    private String endpointInternal;
    @Value(value = "${file.oss.accessKeyId}")
    private String accessKeyId;
    @Value(value = "${file.oss.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 上传文件
     *
     * @param file     文件二进制
     * @param filePath 文件路径，相对于指定的根目录下的子文件路径
     * @return 文件的全路径
     */
    @Override
    public String upload(byte[] file, String filePath) {
        OSSClient client = new OSSClient(schema + endpointInternal, accessKeyId, accessKeySecret);
        client.putObject(bucket, filePath, new ByteArrayInputStream(file));
        client.shutdown();
        return schema + bucket + "." + endpoint + "/" + filePath;
    }

    public void remove(String key) {
        OSSClient client = new OSSClient(schema + endpointInternal, accessKeyId, accessKeySecret);
        client.deleteObject(bucket, key);
        client.shutdown();
    }
}